package com.github.caijh.mall.log.service.impl;

import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.caijh.commons.util.DateRange;
import com.github.caijh.framework.data.redis.Redis;
import com.github.caijh.framework.log.util.LogUtils;
import com.github.caijh.mall.constants.Constants;
import com.github.caijh.mall.log.dao.StoreProductLogDao;
import com.github.caijh.mall.log.model.StoreProductLog;
import com.github.caijh.mall.log.service.StoreProductLogService;
import com.github.caijh.mall.utils.DateUtil;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * StoreProductLogServiceImpl 接口实现
 * +----------------------------------------------------------------------
 * | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
 * +----------------------------------------------------------------------
 * | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
 * +----------------------------------------------------------------------
 * | Author: CRMEB Team <admin@crmeb.com>
 * +----------------------------------------------------------------------
 */
@Service
public class StoreProductLogServiceImpl extends ServiceImpl<StoreProductLogDao, StoreProductLog> implements StoreProductLogService {

    private static final Logger logger = LogUtils.getLogger(StoreProductLogServiceImpl.class);

    @Resource
    private StoreProductLogDao dao;

    @Autowired
    private Redis redis;

    @Override
    public Integer getCountByTimeAndType(String time, String type) {
        LambdaQueryWrapper<StoreProductLog> lqw = new LambdaQueryWrapper<>();
        lqw.eq(StoreProductLog::getType, type);
        DateRange dateLimit = DateUtil.getDateRange(time);
        //时间范围
        if (dateLimit.getStartTime() != null && dateLimit.getEndTime() != null) {
            lqw.between(StoreProductLog::getAddTime, dateLimit.getStartTime(), dateLimit.getEndTime());
        }
        return dao.selectCount(lqw);
    }

    /**
     * task记录保存
     */
    @Override
    public void addLogTask() {
        Long size = redis.getRedisTemplate().opsForList().size(Constants.PRODUCT_LOG_KEY);
        logger.info("StoreProductLogServiceImpl.addLogTask | size: {}", size);
        if (size != null && size > 0) {
            for (int i = 0; i < size; i++) {
                //如果10秒钟拿不到一个数据，那么退出循环
                Object data = redis.getRedisTemplate().opsForList().rightPop(Constants.PRODUCT_LOG_KEY, 10L, TimeUnit.SECONDS);
                if (null == data) {
                    continue;
                }
                try {
                    JSONObject jsonObject = JSON.parseObject(data.toString());
                    addLog(jsonObject);
                } catch (Exception e) {
                    redis.getRedisTemplate().opsForList().leftPush(Constants.PRODUCT_LOG_KEY, data);
                }
            }
        }
    }

    private void addLog(JSONObject jsonObject) {
        StoreProductLog proLog = new StoreProductLog();
        proLog.setProductId(jsonObject.getInteger("product_id"));
        proLog.setUid(jsonObject.getInteger("uid"));
        proLog.setType(jsonObject.getString("type"));
        proLog.setAddTime(jsonObject.getLong("add_time"));
        save(proLog);
    }

}

